import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateCompanyDto } from './dto/create-company.dto';
import { UpdateCompanyDto } from './dto/update-company.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { CompanyEntity } from './entities/company.entity';
import { Brackets, EntityManager, Repository } from 'typeorm';
import { UserEntity } from 'src/user/entities/user.entity';
import { RecordCompanyEntity } from 'src/record_company/entities/record_company.entity';
import { ListCompanyDto } from './dto/list-company.dto';
import { BusinessException } from 'src/common/filter/business-exception/business.exception';

@Injectable()
export class CompanyService {
  constructor(
    @InjectRepository(CompanyEntity)
    private companyRepository: Repository<CompanyEntity>,
    private readonly entityManager: EntityManager,
    @InjectRepository(RecordCompanyEntity)
    private recordCompanyRepository: Repository<RecordCompanyEntity>,
  ) {}
  async create(createCompanyDto: CreateCompanyDto, user: UserEntity) {
    // 事务执行事例
    // return await this.entityManager.transaction(async (manager) => {
    //   const newCompany = manager.create(CompanyEntity, {
    //     ...createCompanyDto,
    //     user_id: user.id,
    //   });
    //   const company = await manager.save(newCompany);
    //   // 创建记录
    //   const newRecord = manager.create(RecordCompanyEntity, {
    //     company_id: company.id,
    //     user_id: company.user_id,
    //     name: company.name,
    //   });
    //   await manager.save(newRecord);
    //   return company;
    // });
    // 不允许重名
    const company = await this.companyRepository.findOne({
      where: { user_id: user.id, name: createCompanyDto.name, is_delete: 0 },
    });
    if (company) throw new BusinessException('公司已存在');

    const newCompany = this.companyRepository.create(createCompanyDto);
    newCompany.user_id = user.id;
    return await this.companyRepository.save(newCompany);
  }
  // 分页获取
  async findByPage(searchParam: ListCompanyDto, user: UserEntity) {
    const { current, size } = searchParam;
    const list = await this.companyRepository
      .createQueryBuilder()
      .where({ user_id: user.id, is_delete: 0 })
      .andWhere(
        new Brackets((qb) => {
          if (!searchParam.name) return qb;
          return qb.where('name like :name', { name: `%${searchParam.name}%` });
        }),
      )
      .orderBy('create_time', 'DESC')
      .skip((current - 1) * size)
      .take(size)
      .getManyAndCount();

    return {
      list: list[0],
      total: list[1],
      pages: Math.ceil(list[1] / size),
    };
  }
  // 获取全部
  async findAll(user: UserEntity, select: string = '') {
    const handle = this.companyRepository
      .createQueryBuilder()
      .orderBy('create_time', 'DESC')
      .where({ user_id: user.id, is_delete: 0 });
    if (select !== '') handle.select(select);
    return (await handle.execute()) as CompanyEntity[];
  }

  findOne(id: string) {
    return this.companyRepository.findOne({ where: { id, is_delete: 0 } });
  }

  async update(
    id: string,
    updateCompanyDto: UpdateCompanyDto,
    user: UserEntity,
  ) {
    const company = await this.companyRepository.findOne({
      where: { user_id: user.id, id, is_delete: 0 },
    });
    if (!company) {
      throw new BusinessException('公司不存在');
    }
    if (company.name === updateCompanyDto.name)
      throw new BusinessException('公司名称无变化');

    const anotherCompany = await this.companyRepository.findOne({
      where: { user_id: user.id, name: updateCompanyDto.name, is_delete: 0 },
    });
    if (anotherCompany) throw new BusinessException('公司名称已存在');

    company.name = updateCompanyDto.name;
    return await this.companyRepository.save(company);
  }

  async remove(id: string, user: UserEntity) {
    const company = await this.companyRepository.findOne({
      where: { id, user_id: user.id, is_delete: 0 },
    });
    if (!company) throw new BusinessException('公司不存在');
    company.is_delete = 1;
    return await this.companyRepository.save(company);
  }
}
